<template>
  <div class="app-container">
    <!-- 添加照片对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="deviceType==10?'配置信标':title" :visible.sync="open" width="520px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="网关">
          <el-input
            v-model="form.deviceCode"
            placeholder="请输入设备名称"
            clearable
            disabled
            size="small"
          />
        </el-form-item>
        <el-row v-for="(item,index) in form.setting" :key="item.key">
          <el-form-item v-if="item.key=='wg_low_engery_work_time'&& isLowPowerTime=='true'" :label="item.name" :prop="'setting.'+index+'.value'">
            <el-time-picker
              @change="(val)=>{changeWorkTime(val,item)}"
              is-range
              v-model="workTime"
              value-format="HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
            <el-input
              v-model="item.value"
              placeholder="请输入名称"
              size="small"
              @input="$forceUpdate()"/>
          </el-form-item>
          <el-form-item v-else-if="item.key!=='wg_low_engery_work_time'"  :label="item.name" :prop="'setting.'+index+'.value'">
            <el-input
              v-model="item.value"
              placeholder="请输入名称"
              size="small"
              type="number"
              @input="$forceUpdate()"
            v-if="item.key=='ble_wristband_scan_interval'"/>
            <el-input
              v-model="item.value"
              placeholder="请输入负数"
              v-enterFloat="{ negative: true }"
              size="small"
              @input="$forceUpdate()"
              v-else-if="item.key=='ble_wristband_rssi_min'" />
            <el-radio-group v-model="item.value" v-else-if="item.key=='wg_role'&&deviceType!==10"
                            @input="$forceUpdate()" @change="changeTypes">
              <el-radio :label="'beacon'">信标</el-radio>
              <el-radio :label="'gateway'">物联网网关</el-radio>
              <el-radio :label="'mix'">信标+网关</el-radio>
            </el-radio-group>
            <el-radio-group v-model="item.value" v-else-if="item.key=='wg_low_engery_enable'" @change="changeEngery" @input="$forceUpdate()" :disabled="flag">
              <el-radio :label="'true'">开启</el-radio>
              <el-radio :label="'false'">关闭</el-radio>
            </el-radio-group>

            <el-input
              v-model="item.value"
              placeholder="请输入名称"
              size="small"
              @input="$forceUpdate()"
              v-else/>
          </el-form-item>

        </el-row>
        <div v-if="showDevicelist&&deviceType!=10">
        <el-row v-for="(item,index) in form.gatewayConfig" :key="index" >
          <el-row>
            <el-col :span="18">
              <el-form-item label="设备类型" :prop="'gatewayConfig.'+index+'.model'" >
                <el-select v-model="item.model" placeholder="请选择设备类型" @change="changedeviceTypes($event,item,index)">
                  <el-option
                    v-for="dict in dict.type.switch_panel"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                    size="small">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" icon="el-icon-delete" size="mini" @click="deletedevice(item,index)">删除</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="设备地址" :prop="'gatewayConfig.'+index+'.addr'" >
                <el-input v-model="item.addr"
                          placeholder="请输入设备地址"
                          size="small"
                          @input="$forceUpdate()"/>
              </el-form-item>
            </el-col>
          </el-row>

          <div v-for="(infor,i) in item.ports" :key="i" :class="infor.deviceType=='CURTAIN_SWITCH'?'configlist':''">
            <el-row>
              <el-col :span="18">
                <el-form-item  :label="'端口'+(i+1)" :prop="'gatewayConfig.'+index+'.ports.'+i+'.deviceName'" >
                  <el-input
                    v-model="infor.deviceName"
                    placeholder="请输入名称"
                    size="small"
                    @input="$forceUpdate()"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" style="padding-left: 5px;padding-top: 6px;">
                <el-tag>{{infor.deviceType=='LIGHT'?'灯':infor.deviceType=='LIGHT'?'灯':infor.deviceType=='CURTAIN_SWITCH'?'窗帘':infor.deviceType=='CURTAIN'?'睡眠室窗帘':''}}</el-tag>
              </el-col>
            </el-row>
            <el-form-item  :label="'窗帘地址'+(i+1)" :prop="'gatewayConfig.'+index+'.ports.'+i+'.curtainAddr'" v-if="infor.deviceType=='CURTAIN_SWITCH'">
              <el-input
                v-model="infor.curtainAddr"
                placeholder="请输入地址"
                size="small"
                @input="$forceUpdate()"
              />
            </el-form-item>
          </div>
        </el-row>
        </div>
      </el-form>
      <div><el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
        v-if="showDevicelist"
      >新增</el-button></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addStudenPhoto, listgrowphoto, updatesphotoList } from '@/api/base/grow'
import { selectClazz } from '@/api/base/clazz'
import { listPhotogl } from '@/api/base/gardensystem'
import {getConfigKey} from "@/api/system/config";
import {saveGateConfig} from "@/api/base/device";

export default {
  name: "settinggateway",
  dicts:['switch_panel'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "配置网关",
      open:false,
      // form:{},
      rules:{},
      flag:false,//判断功能低耗
      showDevicelist:false,//设备列表
      workTime:'',
      isLowPowerTime:'false'
    };
  },
  props: {
    form: {
      type: Object,
      default: () => {}
    },
    deviceType:{
      type: Number,
      default: null,
    }
  },
  watch:{
    form:{
      deep: true,
      immediate: true,
      handler(val) {

        if(val.gatewayConfig.length==0){
          this.pushgateway()
        }
        if(val.setting){
          console.log('val.setting',val.setting);
          if(val.setting.find(item=>item.key=='wg_role')){
            let name=val.setting.find(item=>item.key=='wg_role').value
            this.changeTypes(name)
          }
          if(val.setting.find(item=>item.key=='wg_low_engery_enable'&& item.value == 'true')){
            this.isLowPowerTime = 'true'
          }
        }

      }
    },
  },
  directives: {
    enterFloat: {
      update: function (el, {value, modifiers}, vnode) {
        try {
          let a_el = el.children[0];
          let first = a_el.value.charAt(0);
          // debugger;
          // console.log(a_el)
          if (!a_el.value) {
            return false;
          }
          a_el.value = a_el.value
            .replace(/[^\d.]/g, '')
            .replace(/\.{2,}/g, '.')
            .replace('.', '$#$')
            .replace(/\./g, '')
            .replace('$#$', '.')
            .replace(/^(\-)*(\d+)\.(\d{1,10}).*$/, '$1$2.$3')
            .replace(/^\./g, '')
          if (a_el.value.indexOf(".") < 0 && a_el.value != "") {
            a_el.value = parseFloat(a_el.value);
          }
          if (value && value.negative && first == "-") {
            a_el.value = "-" + a_el.value;
          }else{
            //如果直接写了正数默认加个负
            a_el.value = "-" + a_el.value;
          }
          a_el.dispatchEvent(new Event(modifiers.lazy ? "change" : "input"));
        } catch (e) {
        }
      },
    },
  },
  created() {
  },
  methods: {
    // 选择低功耗模式工作时间
    changeWorkTime(val,item){
      console.log('val',val,item.value);
      if(val){
        item.value = item.value?(item.value+','+val.join('-')):(item.value + val.join('-'))
      }
      this.$forceUpdate()
    },
    // 选择是否开启低功耗模式
    changeEngery(val){
        this.isLowPowerTime = val
    },
    /**删除设备**/
    deletedevice(item,index){
      console.log(this.form.gatewayConfig)
      this.form.gatewayConfig.splice(index,1)
      this.$forceUpdate()
    },
    /**网关功能切换**/
    changeTypes(val){
      if(val=='gateway'){
        this.flag=true
        this.showDevicelist=true
      }else if(val=='mix'){
        this.showDevicelist=true
        this.flag=false
      }else{
        this.showDevicelist=false
        this.flag=false
      }
    },
    /**设备类型切换**/
    changedeviceTypes(val,item,index){
      this.form.gatewayConfig = Object.assign([], this.form.gatewayConfig, this.form.gatewayConfig)
      // this.form.gatewayConfig=JSON.parse(JSON.stringify(this.form.gatewayConfig))
      let data={}
      this.getConfigKey(val).then(res=>{
        data=JSON.parse(res.msg);
        //遍历删除第一个默认的
        this.form.gatewayConfig.forEach((infor,index)=>{
          if(infor.hasOwnProperty("devicetypes")){
            this.form.gatewayConfig.splice(index,1)
          }
        })
        this.form.gatewayConfig[index]=data
        this.$forceUpdate()
      })

    },

    /**如果为空塞一个值*/
    pushgateway(){
      let gatewayConfig={devicetypes:''}
      console.log(this.form.gatewayConfig)
      if(this.form.gatewayConfig.length==0){
        this.form.gatewayConfig.push(gatewayConfig)
        // this.changeTypes('beacon')
      }else{
        this.form.gatewayConfig.some(item=>{
          console.log(item.hasOwnProperty("devicetypes"))
          if(!item.hasOwnProperty("devicetypes")){
            this.form.gatewayConfig.push(gatewayConfig)
            return true
          }
        })
      }
      this.$forceUpdate()
      // this.$set(this.form,'gatewayConfig',gatewayConfig)
      // this.form.gatewayConfig=gatewayConfig
    },
    /**新增*/
    handleAdd(){
      this.pushgateway()
    },
    // 关闭弹窗
    cancel() {
      this.$emit('getList');
      this.open = false;

    },
    //打开照片弹窗
    showdialog(){
      this.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params={
            gatewaySn:this.form.deviceCode,
            deviceList:this.form.gatewayConfig,
            settings:this.form.setting
          }
          let paramsflag=0
          this.form.gatewayConfig.some(item=>{
            if(item.hasOwnProperty("devicetypes")){
              paramsflag=1
              return true
            }
          })
          this.form.setting.some(item=>{
            if(item.value=="beacon"){
              paramsflag=1
              return true
            }
          })
          if(paramsflag){
            params.deviceList=[]
          }
          saveGateConfig(params).then(res=>{
            if(res.code==200){
              this.msgSuccess("保存成功");
              this.open = false;
              this.$emit('getList');
            }else{
              this.msgError(res.msg)
            }
          })

        }
      });
    },
  }
};
</script>
<style lang="scss" scoped>
.el-dialog .el-image{
  left: 50%;
  transform: translate(-50%,0);
}
.radiostyle{
  position: absolute;
  z-index: 10;
  right: 10px;
  top: 10px;
}
.configlist{
  //border-top: 1px solid #eee;
}
::v-deep .el-dialog__body .el-input--small .el-input__inner{
  width: 219px;
}
::v-deep .el-date-editor--daterange.el-input, .el-date-editor--daterange.el-input__inner, .el-date-editor--timerange.el-input, .el-date-editor--timerange.el-input__inner{
  width: 219px;
}
//.el-dialog__body .el-select,.el-dialog__body .el-date-editor{
//  width: 100%;
//}
</style>
